package com.startest.sms.web;

import com.startest.sms.utils.PictureCaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * Created by cly on 2018/12/3.
 */
@RestController
@RequestMapping("")
public class RootController {

    private static final Logger logger = LoggerFactory.getLogger(RootController.class);

    /**
     * 验证输入的验证码
     * @param request
     * @param response
     * @param val
     * @return
     */
    @RequestMapping(value = "/check",method = RequestMethod.POST)
    public Object check(HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam("val") String val){
        String str = (String) request.getSession().getAttribute("captchaText");
        if(!val.equalsIgnoreCase(str)){
            return "验证码错误";
        }else {
            return 1;
        }
    }

    /**
     * 生成验证码图片
     * @param request
     * @param response
     */
    @RequestMapping(value = "/captcha")
    public void getcaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","No-cache");
        response.setContentType("image/jpeg");
        //代理服务器/浏览器   缓存时限
        response.setDateHeader("Expires",0);
        PictureCaptcha captcha = new PictureCaptcha();
        BufferedImage image = captcha.getCaptcha();
        String captchaText = captcha.getText();
        System.out.println(captchaText);
        request.getSession().setAttribute("captchaText",captchaText);
        captcha.output(image,response.getOutputStream());

    }

}
